package meterMonitor.framework.auth;
 
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import meterMonitor.consts.DefinesConst;
import meterMonitor.framework.context.CurrentUser;
import meterMonitor.framework.context.SessionContext;
import meterMonitor.util.ResourceConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
  
public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {
	 final  Logger logger = LoggerFactory.getLogger(getClass());
 

		@Autowired
		protected ResourceConfig resourceConfig;
		
	    @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

			String requestUrl = request.getRequestURL().toString();
			if (requestUrl.endsWith("/login.do")||requestUrl.endsWith("/doLogin.do")||requestUrl.endsWith("/logout.do")){
				return true;
			}

			CurrentUser user = SessionContext.getCurrentUser(); //原始登录信息 无效
			if (user == null) {
				return false;
			}

            HandlerMethod handler2=(HandlerMethod) handler;
	        FireAuthority fireAuthority = handler2.getMethodAnnotation(FireAuthority.class);
	 
	        if(null == fireAuthority){
	            //没有声明权限,放行
	            return true;
	        }
	        
//	        if(SessionContainer.getOperatorId() == null) {
//	            //throw new NoPermissionException("你还没有登陆！");//&redirectUrl=当前请求的url
//	            request.getRequestDispatcher(" http://passport.zhaogangrentest.com/login?zg_sso_system_alias=interest.zhengxin.management.ui").forward(request, response);
//	        }

	        String authCode=fireAuthority.authorityTypes()[0].getIndex();

			boolean aflag=hasAuth(authCode);
	        if(!aflag){//没有权限

				if(request.getHeader("x-requested-with") != null &&
						"XMLHttpRequest".equals(request.getHeader("x-requested-with"))){//ajax请求
					//response.setHeader("sessionstatus", "timeout");
					//ajax类型的登录提示
					response.setCharacterEncoding("utf-8");
					// response.setContentType("application/json;charset=UTF-8");
					response.setHeader("Content-Type", "application/json;charset=UTF-8");
					OutputStream out = response.getOutputStream();
					//String strJsob = IOUtils.toString(out,CommonConsts.ENCODING);

					PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
					pw.println("{\"code\":-1,\"success\":false,\"msg\":\"权限不足！\"}");
					pw.flush();
					pw.close();
				}
			    else {
					//跳转页面
                 	 request.getRequestDispatcher("/authFail.do").forward(request, response);
	            }

//	            if (fireAuthority.resultType() == ResultTypeEnum.page) {
//	                 //跳转页面
//                	 request.getRequestDispatcher("/authFail.do").forward(request, response);
//	            } else if (fireAuthority.resultType() == ResultTypeEnum.json) {
//	                //ajax类型的登录提示
//	                response.setCharacterEncoding("utf-8");
//	               // response.setContentType("application/json;charset=UTF-8");
//	                response.setHeader("Content-Type", "application/json;charset=UTF-8");
//	                OutputStream out = response.getOutputStream();
//	            	//String strJsob = IOUtils.toString(out,CommonConsts.ENCODING);
//
//	                PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
//	                pw.println("{\"code\":-1,\"success\":false,\"msg\":\"权限不足！\"}");
//	                pw.flush();
//	                pw.close();
//	            }
	 
	            return false;
	 
	        }
	        return true;
	    }

	    private boolean hasAuth(String authCode){
	    	boolean hasAuth=false;
			CurrentUser user = SessionContext.getCurrentUser(); //原始登录信息 无效
			if(user!=null){
				List<String> codeList=user.getUserAuthList();
				if(codeList!=null&&codeList.size()>0){
					for(String code :codeList){
						if(code.equals(authCode)){
							hasAuth=true;
							break;
						}
					}
				}
			}
			return hasAuth;
	    }
}
